package com.linkage.jz.bankruptcy.fragment.Vote;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.Vote.ProVoteVotersDetailGroupsAdapter;
import com.linkage.jz.bankruptcy.adapter.expand.adapter.BaseExpandableAdapter;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteVotersDetail;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteVotersDetailGroup;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.BundleUtils;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.RecyclerViewNoBugLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 表决人详情Tab之已表决列表,已参会未表决列表和未参会列表（分组）
 * see https://lanhuapp.com/web/#/item/project/board/detail?pid=19ffdabe-41f1-40c0-91af-37b491d5d596&project_id=19ffdabe-41f1-40c0-91af-37b491d5d596&image_id=26a11528-8dbd-48be-9c4f-6ef466ea789d
 */
public class ProVoteVotersWithGroupFragment extends ProVoteBaseFragment {

    public static final String ARG_PARAM_STATUS = "arg_param_status";
    public static final String ARG_PARAM_OPEN_GROUP = "arg_param_open_group";
    private int STATUS = 1;//1-已表决  2-已参会未表决  3-未参会
    private ProVote proVote;
    private View rootView;

    private TextView proVoteTotalVoter;
    private LRecyclerView mRecyclerView;
    private RelativeLayout emptyView;
    private ProVoteVotersDetailGroupsAdapter mDataGroupAdapter;
    private LRecyclerViewAdapter mGroupAdapter;
    private List<ProVoteVotersDetailGroup> mData;
    private int page = 1;
    private String openGroupId;
    private String userToken;

    public static ProVoteVotersWithGroupFragment newInstance(int status, String openGroupId) {
        ProVoteVotersWithGroupFragment fragment = new ProVoteVotersWithGroupFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM_STATUS, status);
        args.putString(ARG_PARAM_OPEN_GROUP, openGroupId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        proVote = BundleUtils.getProVote();
        STATUS = getArguments().getInt(ARG_PARAM_STATUS, 1);
        openGroupId = getArguments().getString(ARG_PARAM_OPEN_GROUP, "");
        mData = new ArrayList<>();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_pro_vote_voters_details, container, false);
        }
        proVoteTotalVoter = rootView.findViewById(R.id.pro_vote_total_voter);
        proVoteTotalVoter.setText("已表决：" + proVote.getVote() + "人");
        mRecyclerView = rootView.findViewById(R.id.list);
        emptyView = rootView.findViewById(R.id.empty);
        mDataGroupAdapter = new ProVoteVotersDetailGroupsAdapter(getActivity(),mData);
        mDataGroupAdapter.setExpandCollapseListener(new BaseExpandableAdapter.ExpandCollapseListener() {
            @Override
            public void onListItemExpanded(int position) {
                Toast.makeText(getActivity(), "展开position=" + position, Toast.LENGTH_SHORT);
            }

            @Override
            public void onListItemCollapsed(int position) {
                Toast.makeText(getActivity(), "关闭position=" + position, Toast.LENGTH_SHORT);
            }
        });
        mDataGroupAdapter.setRequestChild(new ProVoteVotersDetailGroupsAdapter.ParentReqChildListener() {
            @Override
            public void onReq(ProVoteVotersDetailGroup pg) {
                getVotersWithNoGroup(pg);
            }
        });
        mGroupAdapter = new LRecyclerViewAdapter(mDataGroupAdapter);

        mRecyclerView.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(getActivity()));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader); //设置下拉刷新Progress的样式
        mRecyclerView.setArrowImageView(com.github.jdsjlzx.R.drawable.progressbar);  //设置下拉刷新箭头
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchData();
            }
        });
        mRecyclerView.forceToRefresh();
        return rootView;
    }

    private void fetchData() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        getVotersWithGroup();
    }

    private void getVotersWithGroup() {
        showLoading();
        mRecyclerView.setAdapter(mGroupAdapter);
        mRecyclerView.setLoadMoreEnabled(false);
        Network.getAPIService()
                .getVoteGroup(userToken, proVote.getId(), String.valueOf(STATUS),proVote.getDefaultAgreed(), page, 200)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        LogUtil.e("--response--", json.toString());
                        JsonArray data = json.getAsJsonObject("data").getAsJsonArray("list");
                        List<ProVoteVotersDetailGroup> networkData = ProVoteVotersDetailGroup.parse(data);
                        mData.clear();//不分页
                        mData.addAll(networkData);
                        mRecyclerView.refreshComplete(200);
                        mGroupAdapter.notifyDataSetChanged();
                        if(mData != null && mData.size() > 0) {
                            if(!TextUtils.isEmpty(openGroupId)) {
                                int index = -1;
                                for(int i=0;i<mData.size();i++) {
                                    ProVoteVotersDetailGroup pg = mData.get(i);
                                    if(openGroupId.equals(pg.getId())) {
                                        index = i;
                                        break;
                                    }
                                }
                                ProVoteVotersDetailGroup pg = mData.get(index);
                                if (!pg.isRequestChild()) {
                                    getVotersWithNoGroup(pg);
                                }
                            }else {
                                ProVoteVotersDetailGroup pg = mData.get(0);
                                if (!pg.isRequestChild()) {
                                    getVotersWithNoGroup(pg);
                                }
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }
                });
    }

    private void getVotersWithNoGroup(ProVoteVotersDetailGroup group) {
        if(group.isRequestChild())return;
        group.setRequestChild(true);
        showLoading();
        Network.getAPIService()
                .getVoteParticipants(userToken, proVote.getId(), proVote.getBankruptcyProjectId(), group.getId(), STATUS,proVote.getDefaultAgreed(), page, 100)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        LogUtil.e("--response--", json.toString());
                        JsonArray data = json.getAsJsonObject("data").getAsJsonObject("pageData").getAsJsonArray("list");
                        List<ProVoteVotersDetail> networkData = ProVoteVotersDetail.parse(data, group.getId());
                        group.setChilds(networkData);
                        mRecyclerView.refreshComplete(20);
                        mGroupAdapter.notifyDataSetChanged();
                        mDataGroupAdapter.expandItem(group);
                    }

                    @Override
                    public void onCompleted() {
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }
                });
    }

}
